package net.wanho.shop.interceptor;

import net.wanho.shop.common.UserConstant;
import net.wanho.shop.util.CurrentUtil;
import net.wanho.shop.util.JwtUtil;
import org.springframework.util.ObjectUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登录拦截器
 */
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String authorization = request.getHeader("Authorization");
        if (ObjectUtils.isEmpty(authorization)) {
            throw new RuntimeException("请先登录再操作");
        }
        // 去掉Bearer
        String token = authorization.replace("Bearer ", "");

        if (!JwtUtil.valid(token)) {
            throw new RuntimeException("token无效，请重新登录");
        }

        // 获取用户的id
        Integer id = JwtUtil.parseInteger(token, UserConstant.USER_ID);
        CurrentUtil.setId(id);

        return true;
    }
}
